import { defineStore } from 'pinia'
import { logout } from '@/api/auth'

interface User {
  id: string
  username: string
  email: string
  avatar?: string
  roles?: string[]
}

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: localStorage.getItem('access_token'),
    refreshToken: localStorage.getItem('refresh_token'),
    user: JSON.parse(localStorage.getItem('user_info') || 'null'),
  }),

  actions: {
    setToken(newToken: string) {
      this.token = newToken
      localStorage.setItem('access_token', newToken)
    },

    setRefreshToken(newRefreshToken: string) {
      this.refreshToken = newRefreshToken
      localStorage.setItem('refresh_token', newRefreshToken)
    },

    setUser(userData: User) {
      this.user = userData
      localStorage.setItem('user_info', JSON.stringify(userData))
    },

    clearAuth() {
      this.token = null
      this.refreshToken = null
      this.user = null
      localStorage.removeItem('access_token')
      localStorage.removeItem('refresh_token')
      localStorage.removeItem('user_info')
    },

    isAuthenticated(): boolean {
      return this.token !== null
    },

    async logout() {
      try {
        // 使用封装的request工具调用退出接口
        await logout()

        // 只有后端成功退出才清理本地状态
        this.clearAuth()
        return true
      } catch (error: any) {
        console.error('登出API调用失败:', error)
        // 退出失败时不清理本地状态，保持用户登录状态
        // 根据后端是否实现logout接口来决定是否允许退出
        // 如果后端没有实现logout接口，我们允许前端直接退出
        if (error.message?.includes('404') || error.message?.includes('Not Found')) {
          console.warn('后端未实现logout接口，允许前端直接退出')
          this.clearAuth()
          return true
        }
        throw new Error('退出失败，请重试')
      }
    },
  },
})
